package kr.hyunist.androidcomplete02saeildamil.ch30;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.Toast;

public class NewsServiceEx extends Service {
	boolean mQuit;

	@Override
	public void onCreate() {
		super.onCreate();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();

		Toast.makeText(this, "Service end", 0).show();
		mQuit = true;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		super.onStartCommand(intent, flags, startId);

		mQuit = false;
		NewsThread thread = new NewsThread(this, mHandler);
		thread.start();
		return START_STICKY;

	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	class NewsThread extends Thread {
		NewsServiceEx mParent;
		Handler mHandler;

		String[] arNews = { "권기현! 천재로 밝혀져..", "권기현! 구글을 인수!",
				"이래되야 될껀데..", "권기현! 도적 만랩을 찍다!", "권기현! 이래가 될일이가?!!", "권기현! 교만하지말고 끝까지 열심히.." };

		public NewsThread(NewsServiceEx parent, Handler handler) {
			super();
			this.mParent = parent;
			this.mHandler = handler;
		}

		@Override
		public void run() {
			for (int idx = 0; mQuit == false; idx++) {
				Message msg = new Message();
				msg.what = 0;
				msg.obj = arNews[idx % arNews.length];
				mHandler.sendMessage(msg);
				try {
					Thread.sleep(5000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}

	}

	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == 0) {
				String news = (String) msg.obj;
				Toast.makeText(NewsServiceEx.this, news, 0).show();
			}
		};
	};
}
